package com.banmoon.algorithm.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Question599 {

    public static void main(String[] args) {
        String[] list1 = {"Shogun","Tapioca Express","Burger King","KFC"};
        String[] list2 = {"Piatti","The Grill at Torrey Pines","Hungry Hunter Steakhouse","Shogun"};
        String[] strings = findRestaurant(list1, list2);
        System.out.println(Arrays.toString(strings));
    }

    public static String[] findRestaurant(String[] list1, String[] list2) {
        ArrayList<String> list = new ArrayList<>();
        int currentMinIndex = list1.length + list2.length - 2;
        A: for (int i = list1.length-1; i >= 0; i--) {
            for (int j = list2.length-1; j >= 0; j--) {
                if (list1[i].equals(list2[j]) && i+j<=currentMinIndex) {
                    if(i+j<currentMinIndex){
                        list.clear();
                        currentMinIndex = i+j;
                    }
                    list.add(list1[i]);
                    continue A;
                }
            }
        }
        return list.toArray(new String[0]);
    }

    public static String[] findRestaurant1(String[] list1, String[] list2) {
        return IntStream.range(0, list1.length + list2.length)
                .boxed()
                .collect(Collectors.groupingBy(i -> i < list1.length ? list1[i] : list2[i - list1.length]))
                .entrySet()
                .stream()
                .filter(entry -> entry.getValue().size() == 2)
                .collect(Collectors.groupingBy(entry ->
                                entry.getValue().get(0) + entry.getValue().get(1),
                                TreeMap::new,
                                Collectors.mapping(Map.Entry::getKey, Collectors.toList()))
                )
                .values()
                .iterator()
                .next()
                .toArray(new String[0]);
    }




}
